/**
 * 导出管理器 - 处理文件导出功能
 */
class ExportManager {
    constructor() {
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadLibraries();
    }

    bindEvents() {
        // 绑定导出按钮事件
        document.getElementById('export-pdf')?.addEventListener('click', () => {
            this.exportToPDF();
        });

        document.getElementById('export-word')?.addEventListener('click', () => {
            this.exportToWord();
        });

        document.getElementById('export-html')?.addEventListener('click', () => {
            this.exportToHTML();
        });
    }

    async loadLibraries() {
        // 动态加载必要的库
        try {
            // 加载jsPDF用于PDF导出
            if (!window.jsPDF) {
                await this.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js');
            }

            // 加载html2canvas用于HTML转图片
            if (!window.html2canvas) {
                await this.loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js');
            }

            // 加载docx库用于Word导出
            if (!window.docx) {
                await this.loadScript('https://unpkg.com/docx@8.2.2/build/index.js');
            }

            console.log('导出库加载完成');
        } catch (error) {
            console.error('导出库加载失败:', error);
        }
    }

    loadScript(src) {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            script.onload = resolve;
            script.onerror = reject;
            document.head.appendChild(script);
        });
    }

    async exportToPDF() {
        try {
            this.showToast('正在生成PDF...', 'info');
            
            const content = this.getMarkdownContent();
            const html = await this.convertMarkdownToHTML(content);
            
            // 创建临时容器
            const container = document.createElement('div');
            container.style.cssText = `
                position: absolute;
                left: -9999px;
                top: -9999px;
                width: 210mm;
                padding: 20mm;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 14px;
                line-height: 1.6;
                color: #333;
                background: white;
            `;
            container.innerHTML = html;
            document.body.appendChild(container);

            // 使用html2canvas转换为图片
            const canvas = await html2canvas(container, {
                scale: 2,
                useCORS: true,
                allowTaint: true,
                backgroundColor: '#ffffff'
            });

            // 创建PDF
            const { jsPDF } = window.jsPDF;
            const pdf = new jsPDF('p', 'mm', 'a4');
            
            const imgData = canvas.toDataURL('image/png');
            const imgWidth = 210;
            const pageHeight = 295;
            const imgHeight = (canvas.height * imgWidth) / canvas.width;
            let heightLeft = imgHeight;
            let position = 0;

            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;

            while (heightLeft >= 0) {
                position = heightLeft - imgHeight;
                pdf.addPage();
                pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
            }

            // 下载PDF
            const filename = this.getFilename('pdf');
            pdf.save(filename);
            
            // 清理
            document.body.removeChild(container);
            this.showToast('PDF导出成功', 'success');
            
        } catch (error) {
            console.error('PDF导出失败:', error);
            this.showToast('PDF导出失败: ' + error.message, 'error');
        }
    }

    async exportToHTML() {
        try {
            this.showToast('正在生成HTML...', 'info');
            
            const content = this.getMarkdownContent();
            const html = await this.convertMarkdownToHTML(content);
            
            const fullHTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown Export</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #fff;
        }
        h1, h2, h3, h4, h5, h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }
        h1 { font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 10px; }
        h2 { font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 8px; }
        h3 { font-size: 1.25em; }
        p { margin-bottom: 16px; }
        code {
            background: #f6f8fa;
            border-radius: 3px;
            font-size: 85%;
            margin: 0;
            padding: 0.2em 0.4em;
        }
        pre {
            background: #f6f8fa;
            border-radius: 6px;
            font-size: 85%;
            line-height: 1.45;
            overflow: auto;
            padding: 16px;
        }
        blockquote {
            border-left: 4px solid #dfe2e5;
            margin: 0;
            padding: 0 16px;
            color: #6a737d;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 16px 0;
        }
        th, td {
            border: 1px solid #dfe2e5;
            padding: 6px 13px;
            text-align: left;
        }
        th {
            background: #f6f8fa;
            font-weight: 600;
        }
        img {
            max-width: 100%;
            height: auto;
        }
        a {
            color: #0366d6;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
${html}
</body>
</html>`;

            // 下载HTML文件
            const blob = new Blob([fullHTML], { type: 'text/html;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = this.getFilename('html');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            this.showToast('HTML导出成功', 'success');
            
        } catch (error) {
            console.error('HTML导出失败:', error);
            this.showToast('HTML导出失败: ' + error.message, 'error');
        }
    }

    async exportToWord() {
        try {
            this.showToast('正在生成Word文档...', 'info');
            
            const content = this.getMarkdownContent();
            
            // 简单的Markdown到Word转换
            const paragraphs = this.parseMarkdownForWord(content);
            
            // 创建Word文档
            const doc = new window.docx.Document({
                sections: [{
                    properties: {},
                    children: paragraphs
                }]
            });

            // 生成并下载
            const buffer = await window.docx.Packer.toBlob(doc);
            const url = URL.createObjectURL(buffer);
            const a = document.createElement('a');
            a.href = url;
            a.download = this.getFilename('docx');
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            this.showToast('Word文档导出成功', 'success');
            
        } catch (error) {
            console.error('Word导出失败:', error);
            this.showToast('Word导出失败，将导出为HTML格式', 'warning');
            // 降级到HTML导出
            this.exportToHTML();
        }
    }

    parseMarkdownForWord(content) {
        const lines = content.split('\n');
        const paragraphs = [];
        
        for (const line of lines) {
            if (line.trim() === '') {
                continue;
            }
            
            // 标题
            if (line.startsWith('# ')) {
                paragraphs.push(new window.docx.Paragraph({
                    text: line.substring(2),
                    heading: window.docx.HeadingLevel.HEADING_1
                }));
            } else if (line.startsWith('## ')) {
                paragraphs.push(new window.docx.Paragraph({
                    text: line.substring(3),
                    heading: window.docx.HeadingLevel.HEADING_2
                }));
            } else if (line.startsWith('### ')) {
                paragraphs.push(new window.docx.Paragraph({
                    text: line.substring(4),
                    heading: window.docx.HeadingLevel.HEADING_3
                }));
            } else {
                // 普通段落
                paragraphs.push(new window.docx.Paragraph({
                    text: line.replace(/\*\*(.*?)\*\*/g, '$1').replace(/\*(.*?)\*/g, '$1')
                }));
            }
        }
        
        return paragraphs;
    }

    async convertMarkdownToHTML(markdown) {
        // 简单的Markdown到HTML转换
        let html = markdown
            // 标题
            .replace(/^### (.*$)/gim, '<h3>$1</h3>')
            .replace(/^## (.*$)/gim, '<h2>$1</h2>')
            .replace(/^# (.*$)/gim, '<h1>$1</h1>')
            // 粗体和斜体
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            // 代码
            .replace(/`(.*?)`/g, '<code>$1</code>')
            // 链接
            .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
            // 图片
            .replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">')
            // 引用
            .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
            // 换行
            .replace(/\n\n/g, '</p><p>')
            .replace(/\n/g, '<br>');
            
        // 包装段落
        html = '<p>' + html + '</p>';
        
        // 清理空段落
        html = html.replace(/<p><\/p>/g, '');
        
        return html;
    }

    getMarkdownContent() {
        if (window.editor && window.editor.getValue) {
            return window.editor.getValue();
        }
        
        // 备用方案：从textarea获取
        const textarea = document.querySelector('#editor textarea');
        if (textarea) {
            return textarea.value;
        }
        
        return '';
    }

    getFilename(extension) {
        const now = new Date();
        const timestamp = now.toISOString().slice(0, 19).replace(/[:-]/g, '');
        return `markdown-export-${timestamp}.${extension}`;
    }

    showToast(message, type = 'info') {
        // 使用现有的toast系统
        if (window.showToast) {
            window.showToast(message, type);
        } else {
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
    }
}

// 初始化导出管理器
window.exportManager = new ExportManager();